package com.steward.server.card.impl;

import com.steward.commons.ConstData;
import com.steward.commons.DataUtils;
import com.steward.commons.Result;
import com.steward.commons.Validation;
import com.steward.dao.card.CardQueryMapper;
import com.steward.dao.mob.MobGiftActiveMapper;
import com.steward.dao.mob.MobRegMapper;
import com.steward.dao.mob.OilCardPayMapper;
import com.steward.dto.card.CardConsumeDTO;
import com.steward.dto.card.OrderDTO;
import com.steward.dto.card.UserCardDTO;
import com.steward.exceptions.StewardException;
import com.steward.model.mob.MobGiftActive;
import com.steward.model.mob.MobGiftActiveExample;
import com.steward.model.mob.MobReg;
import com.steward.model.mob.OilCardPay;
import com.steward.server.card.CardService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CardServiceImpl implements CardService {

	private static Logger logger = Logger.getLogger(CardServiceImpl.class);
	@Resource
	private CardQueryMapper cardQueryMapper;

	@Resource
	private MobGiftActiveMapper mobGiftActiveMapper ;

	@Resource
	private MobRegMapper mobRegMapper ;

	@Resource
	private OilCardPayMapper oilCardPayMapper ;
	@Override
    public Result<List<UserCardDTO>> queryUserCardList(String userId) {
		logger.debug(userId);
		Result<List<UserCardDTO>> result = new Result<List<UserCardDTO>>();
		try {
			if (StringUtils.isEmpty(userId)) {
				throw new StewardException("0x000A00", "传入的参数为空");
			}
			List<UserCardDTO> content = cardQueryMapper.queryUserCardList(userId);
			result.setContent(content);
			result.setCode(ConstData.SUCCESS_CODE);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(ConstData.NOT_FOUND_CODE);
		}
		return result;
	}

	@Override
	public Result<List<CardConsumeDTO>> queryCardConsumeList(String cardId) {
		Result<List<CardConsumeDTO>> result = new Result<List<CardConsumeDTO>>();
		try {
			if (StringUtils.isEmpty(cardId)) {
				throw new StewardException("0x000A00", "传入的参数为空");
			}
			List<CardConsumeDTO> content = cardQueryMapper.queryCardConsumeList(cardId);
			result.setContent(content);
			result.setCode(ConstData.SUCCESS_CODE);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(ConstData.SYS_ERROR);
		}
		return result;
	}

	/**
	 * @param orderId
	 * @return
	 */
	@Override
	public Result<Double> queryOilCardRate(String orderId) {
		Result<Double> result = Result.createResult();
		if(StringUtils.isBlank(orderId)){
			return result.invalidParams("Invalid request parameters supplied");
		}

		//查询激活的折扣
		List<MobGiftActive> giftActives = this.queryMobGiftActive(orderId) ;
		if(CollectionUtils.isEmpty(giftActives)){
			return result.failure("暂时只支持凯利赠送的加油卡，或者 你的加油卡，还未激活");
		}

		//返回折扣值
		result.setContent(giftActives.get(0).getRate()) ;
		return result.success(String.format("你的油卡享受%d折", result.getContent())) ;
	}

	/**
	 * 创建加油卡充值订单
	 * @param UserID 对应手机注册用户表 ID
	 * @param OilCardID 加油卡卡号 16位（中石化规范）
	 * @param pay_amt 充值金额
	 * @param payType 充值类型 1微信 2支付宝
     * @return
     */
	@Override
	public Result<OrderDTO> createOilPayOrder(final String UserID, final String OilCardID, final double pay_amt, final int payType) {
		Result<OrderDTO> result = Result.createResult();
		//判断油卡号码
		if(Validation.isOilCardNo(OilCardID)){
			return result.invalidParams("Invalid request parameters supplied") ;
		}

		List<MobGiftActive> giftActives = this.queryMobGiftActive(OilCardID) ;
		if(CollectionUtils.isEmpty(giftActives)){
			return result.failure("暂时只支持凯利赠送的加油卡，或者 你的加油卡，还未激活");
		}
		//
		MobReg mobReg = mobRegMapper.selectByPrimaryKey(UserID) ;
		if(mobReg == null){
			return result.failure("用户信息不存在！") ;
		}
		//创建油卡订单
		OilCardPay pay = createOilCardPay(UserID, OilCardID, pay_amt, payType) ;
		return result.success("").setContent(new OrderDTO(pay.getId(), pay.getSumBal().doubleValue()));
	}

	private OilCardPay createOilCardPay(String UserID, String OilCardID, double pay_amt, int payType){
		OilCardPay record = new OilCardPay() ;
		record.setId(UUID.randomUUID().toString());
		record.setOrderno(DataUtils.generateOrderNo());
		record.setOilcardid(OilCardID);
		record.setSumBal(BigDecimal.valueOf(pay_amt));
		record.setUpdateOpr(UserID);
		record.setModeCd(0);
		record.setAddDate(new Date());
		record.setAddOprid(UserID);
		oilCardPayMapper.insert(record) ;
		return record ;
	}



	/**
	 * 查询加油卡激活记录
	 * @param cardId
	 * @return
     */
	private List<MobGiftActive> queryMobGiftActive(String cardId){
		MobGiftActiveExample example = new MobGiftActiveExample() ;
		MobGiftActiveExample.Criteria criteria = example.createCriteria();
		criteria.andCardidEqualTo(cardId);
		//criteria.andCardtypeEqualTo(2);
		criteria.andActIndEqualTo(1);
		return mobGiftActiveMapper.selectByExample(example) ;
	}
}
